<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type { DnsNsListItem } from '@/apis/model/dns'
import { Message } from '@arco-design/web-vue'
import {
  postDnsAuthorityNameserverApi,
  updateDnsAuthorityNameserverApi,
} from '@/apis/modules/dns'

interface IProp {
  record: DnsNsListItem
}
const props = withDefaults(defineProps<IProp>(), {})
const emit = defineEmits(['reload'])
const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref<FormInstance>()
const formState = ref({
  remark: '',
  hostname: '',
})

const rules: Record<string, FieldRule> = {}

async function handleOpen() {
  if (props.record) {
    formState.value.remark = props.record.remark
    formState.value.hostname = props.record.hostname
  }
}
const loading = ref(false)
async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error)
    return false
  const fn = props.record
    ? updateDnsAuthorityNameserverApi
    : postDnsAuthorityNameserverApi
  const data = props.record
    ? { id: props.record.id!, ...formState.value }
    : formState.value
  loading.value = true
  await fn(data)
    .then(() => {
      Message.success('操作成功')
    })
    .finally(() => (loading.value = false))
}

function handleClose() {
  formRef.value?.resetFields()
  emit('reload')
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    title="编辑备注"
    :width="480"
    ok-text="保存"
    :mask-closable="false"
    :loading="loading"
    :before-open="handleOpen"
    :before-ok="handleSubmit"
    :before-close="handleClose"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :rules="rules"
      :model="formState"
    >
      <a-form-item
        label=""
        field="remark"
        asterisk-position="end"
      >
        <a-textarea
          v-model="formState.remark"
          :max-length="200"
          show-word-limit
          :auto-size="{ maxRows: 5, minRows: 5 }"
          placeholder="请输入备注"
        />
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>
